package com.hoshiicloud.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.TreeMap;

/**
 * 签名工具类
 * @author Mr.wu
 */
@Slf4j
public class SignUtil {

    //暂时定义为常量
    public static final String SIGN_SECRECT_KEY="098f6bcd4621d373cade4e832627b4f6";

    /**
     * @param param
     * @param key
     * @return java.lang.String
     * @author: Mr.wu
     * @descripton: 生成md5签名字符串
     * @date: 16:30 2019/5/27
     */
    public static String sign(TreeMap<String, String> param, String key) {

        StringBuffer paramstr = new StringBuffer();

        for (String pkey : param.keySet()) {
            String pvalue = String.valueOf(param.get(pkey));
            if (StringUtils.isNotBlank(pvalue) && !pkey.equals("sign")) {// 空值不传递，不签名
                paramstr.append(pkey + "=" + pvalue + "&"); // 签名原串，不url编码
            }
        }
        String paramSrc = paramstr.substring(0, paramstr.length() - 1);

        log.info(paramSrc);
        String sign = DigestUtils.md5(paramSrc + "&key=" + key);
        return sign;

    }

    public static TreeMap<String, String> objectToMap(Object obj) throws Exception {
        if (obj == null)
            return null;

        TreeMap<String, String> map = new TreeMap<>();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            String value = (getter != null && getter.invoke(obj) !=null) ? getter.invoke(obj).toString() : null;
            if (value != null) {
                map.put(key, value);
            }

        }

        return map;
    }
}
